<template>
  <div class="pets-list">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>宠物管理</h2>
          <div class="button-group">
            <el-button 
              v-if="authStore.userRole !== '用户'"
              type="danger" 
              @click="handleBatchDelete"
              :disabled="selectedIds.length === 0"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button 
              v-if="authStore.userRole !== '用户'"
              type="primary" 
              @click="$router.push('/pets/add')"
            >
              <el-icon><Plus /></el-icon>
              添加宠物
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="宠物名称">
          <el-input v-model="queryForm.petName" placeholder="请输入宠物名称" clearable />
        </el-form-item>
        <el-form-item label="宠物类型">
          <el-select v-model="queryForm.petType" placeholder="请选择宠物类型" clearable style="width: 180px;">
            <el-option label="猫" value="猫" />
            <el-option label="狗" value="狗" />
            <el-option label="兔子" value="兔子" />
            <el-option label="鸟" value="鸟" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="queryForm.username" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="客户电话">
          <el-input v-model="queryForm.phone" placeholder="请输入客户电话" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 添加勾选框列 -->
        <el-table-column type="selection" width="55" align="center" />
        
        <el-table-column prop="petId" label="宠物编号" width="100" />
        <el-table-column prop="userId" label="客户编号" width="100" />
        <el-table-column prop="petName" label="宠物名字" width="120" />
        <!-- 新增宠物图片列 -->
        <el-table-column label="宠物图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.photoUrl"
              style="width: 80px; height: 80px; border-radius: 4px;"
              :src="row.photoUrl"
              :preview-src-list="[row.photoUrl]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="no-image">暂无图片</div>
          </template>
        </el-table-column>
        <el-table-column prop="petBreed" label="品种" width="120" />
        <el-table-column prop="petType" label="类型" width="80" />
        <el-table-column prop="petGender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.petGender === 'MALE' ? 'primary' : 'danger'">
              {{ row.petGender === 'MALE' ? '公' : '母' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="petBirth" label="出生日期" width="120" />
        <el-table-column prop="petColor" label="毛色" width="100" />
        <el-table-column prop="petWeight" label="体重(kg)" width="100" />
        <el-table-column prop="petNeuter" label="是否绝育" width="100">
          <template #default="{ row }">
            {{ row.petNeuter ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="petNotes" label="重要备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column 
          v-if="authStore.userRole !== '用户'"
          label="操作" 
          width="180" 
          fixed="right"
        >
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Picture } from '@element-plus/icons-vue'
import { petsApi } from '@/api'
import { useAuthStore } from '@/stores/auth'
import type { Pets, PetsQuery } from '@/types'
import { handlePageResponse } from '@/utils/pagination'

const router = useRouter()
const authStore = useAuthStore()

// 添加调试信息
console.log('PetsList - authStore.userRole:', authStore.userRole)
console.log('PetsList - authStore.user:', authStore.user)
console.log('PetsList - authStore.user?.permissions:', authStore.user?.permissions)

// 查询表单
const queryForm = reactive<Omit<PetsQuery, 'pageNum' | 'pageSize'>>({
  petName: '',
  petType: '',
  username: '',
  phone: '',
  role: ''
})

// 表格数据
const tableData = ref<Pets[]>([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 选中的宠物ID列表
const selectedIds = ref<number[]>([])

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params: PetsQuery = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...queryForm
    }
    
    const response = await petsApi.getPage(params)
    const pageData = handlePageResponse<Pets>(response)
    
    tableData.value = pageData.records
    pagination.total = pageData.total
    
    // 清空选中项
    selectedIds.value = []
  } catch (error) {
    console.error('获取宠物列表失败:', error)
    ElMessage.error('获取宠物列表失败')
  } finally {
    loading.value = false
  }
}

// 处理选中项变化
const handleSelectionChange = (selection: Pets[]) => {
  selectedIds.value = selection.map(item => item.petId!)
}

// 批量删除宠物
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条宠物记录吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await petsApi.batchDelete(selectedIds.value)
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      fetchData() // 重新加载数据
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    petName: '',
    petType: '',
    username: '',
    phone: '',
    role: ''
  })
  pagination.current = 1
  fetchData()
}

// 编辑
const handleEdit = (row: Pets) => {
  router.push(`/pets/update/${row.petId}`)
}

// 删除
const handleDelete = async (row: Pets) => {
  try {
    await ElMessageBox.confirm(`确定要删除宠物"${row.petName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await petsApi.delete(row.petId!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 监听分页参数变化
watch(
  () => [pagination.current, pagination.size],
  () => {
    fetchData()
  }
)

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.pets-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.button-group {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 图片样式 */
.no-image {
  color: #999;
  font-size: 12px;
  text-align: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
</style>